<template>
  <div class="component-container">
    <el-tree
      v-loading="loading"
      style="max-width: 600px"
      :data="data"
      :props="defaultProps"
      @node-click="handleNodeClick"
      node-key="id"
      default-expand-all
      :accordion="true"
      :expand-on-click-node="false"
      ref="categoryTreeRef"
    >
      <template #default="scope">
        <div class="category-tree-node">
          <div>
            <el-image
              :src="scope.data.iconUrl"
              class="category_node_img"
              v-show="scope.data.level == 3"
            >
              <template #error>
                <div class="image-slot">
                  <i-ep-picture />
                </div>
              </template>
            </el-image>
            <span>{{ scope.data.name }}</span>
          </div>
        </div>
        <div>
          <el-button type="success" link v-show="scope.data.level != 3" @click="addOne(scope.data)"
            >新增</el-button
          >
          <el-button type="warning" link v-show="scope.data.id !== 0" @click="editOne(scope.data)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            link
            v-show="scope.data.id && (!scope.data.children || scope.data.children.length <= 0)"
            @click="handleDelete(scope.data)"
            >删除</el-button
          >
        </div>
      </template>
    </el-tree>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500">
      <el-form :model="formData" :rules="rules" ref="dataFormRef">
        <el-form-item label="上级分类" prop="name">
          <el-input v-model="parent.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="分类图标">
          <SingleUpload />
        </el-form-item>
        <el-form-item label="显示状态">
          <el-radio-group v-model="formData.visible">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="formData.sort" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  listCategories,
  addCategories,
  updateCategories,
  deleteCategories
} from '@/api/pms/category'

const dataFormRef = ref(ElForm)
const categoryTreeRef = ref(ElTree)
const emit = defineEmits(['category-click'])

const stata = reactive({
  loading: false,
  data: [] as Array<any>,
  queryParams: {},
  ids: [],
  formData: {
    id: undefined,
    name: undefined,
    parentId: 0,
    level: undefined,
    iconUrl: undefined,
    visible: 1,
    sort: 100
  },
  dialog: {
    title: '',
    visible: false
  },
  rules: {
    parentId: [
      {
        required: true,
        message: '请选择上级分类',
        trigger: 'blur'
      }
    ],
    name: [
      {
        required: true,
        message: '请输入分类名称',
        trigger: 'blur'
      }
    ]
  },
  parent: {} as any,
  current: {} as any
})

const { loading, data, queryParams, formData, dialog, rules, parent, current } = toRefs(stata)

const defaultProps = {
  label: 'name',
  children: 'children',
  disabled: ''
}
//获取数据
const getData = () => {
  stata.loading = true
  listCategories(stata.queryParams).then((res) => {
    stata.data = [
      {
        id: 0,
        name: '全部分类',
        parentId: 0,
        level: 0,
        children: res.data
      }
    ]
    stata.loading = false
  })
}

const handleNodeClick = (data: any) => {
  const categoryTree = unref(categoryTreeRef)
  const parentNode = categoryTree.getNode(data.parentId)

  stata.parent = {
    id: parentNode.key,
    name: parentNode.label,
    level: data.level
  }
  stata.current = JSON.parse(JSON.stringify(data))
  emit('category-click', data)
}

// 点击添加 打开弹窗
const addOne = (row: any) => {
  console.log(row)

  stata.dialog = {
    title: '新增商品分类',
    visible: true
  }
  stata.formData.id = undefined
  if (row.id != null) {
    stata.parent = {
      id: row.id,
      name: row.name
    }
  }
}

//点击编辑 显示详情
const editOne = (row: any) => {
  handleNodeClick(row)
  console.log(row)
  stata.dialog = {
    title: '编辑商品分类',
    visible: true
  }
  Object.assign(stata.formData, stata.current)
}
//提交
const submitForm = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (stata.formData.id) {
        updateCategories(stata.formData.id, stata.formData).then(() => {
          ElMessage.success('修改成功')
          closeDialog()
          getData()
        })
      } else {
        const parentCategory = stata.parent as any
        stata.formData.parentId = parentCategory.id
        stata.formData.level = parentCategory.level + 1
        addCategories(stata.formData).then(() => {
          ElMessage.success('新增成功')
          closeDialog()
          getData()
        })
      }
    }
  })
}
const handleDelete = (row: any) => {
  // 拼接 如果 row.id 不存在，则使用 stata.ids 的值作为 id 的值。
  const id = [row.id || stata.ids].join(',')
  ElMessageBox.confirm('确认要删除吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteCategories(id).then(() => {
      ElMessage.success('删除成功')
      getData()
    })
  })
}
//关闭弹窗
const closeDialog = () => {
  stata.dialog.visible = false
  dataFormRef.value.resetFields()
}
onMounted(() => {
  getData()
})
</script>

<style scoped lang="scss">
.category {
  &_node {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;

    &_img {
      width: 20px;
      height: 20px;
      margin-top: -5px;
      vertical-align: middle;
    }
  }
}
</style>